package com.icehelper.hades.base.util;


import com.icehelper.hades.base.util.annotation.RequestLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class RequestLogAspect{

	private static final Logger logger = LoggerFactory.getLogger( RequestLogAspect.class );

	@Pointcut( "@annotation(com.icehelper.hades.base.util.annotation.RequestLog)" )
	public void pointcut(){

	}

	@Around( "pointcut()" )
	public Object printLogAspect( ProceedingJoinPoint joinPoint ) throws Throwable{

		Method method = this.getMethod( joinPoint );
		RequestLog requestLog = method.getAnnotation( RequestLog.class );
		Object[] args = joinPoint.getArgs();
		Object result = joinPoint.proceed();
		StringBuilder sb = new StringBuilder();
		String prefix = requestLog.prefix();
		if( StringUtils.isEmpty( prefix ) ){
			prefix = method.getName();
		}
		sb.append( prefix ).append( " - " );
		logger.info( "{},args:{},result:{}", sb, JsonUtil.toString( args ), JsonUtil.toString( result ) );
		return result;
	}

	private Method getMethod( JoinPoint jp ) throws Exception{

		MethodSignature methodSignature = ( MethodSignature )jp.getSignature();
		Method method = methodSignature.getMethod();
		return jp.getTarget().getClass().getDeclaredMethod( method.getName(), method.getParameterTypes() );
	}
}
